/**
Header file to describe the programmable state
of the 14-bit instruction word Microchip PIC microcontrollers, 
such as the pic12F675 or the pic16F676.

Orion Sky Lawlor, olawlor@acm.org, 2003/8/3
*/
#ifndef __OSL_PIC14_H
#define __OSL_PIC14_H

#include <stdio.h>

/** One storage location in the EEPROM has this type: */
typedef unsigned char pic14_ee;

/** One instruction has this type: (but only low 14 bits are used) 
*/
typedef unsigned short pic14_inst;

/** One data or program memory reference has this type:
*/
typedef unsigned short pic14_word;

/** A (program) address has this type:
*/
typedef unsigned int pic14_addr;

/** Program state for pic14-series microcontroller */
typedef struct {
#define pic14_inst_len 0x003ffu /* 1023 words of program */
	/**
	  Regular program memory runs from 0x0000 to 0x03fe.
	*/
	pic14_word inst[pic14_inst_len];
	
#define pic14_ee_len 128u /* 128 bytes of EEPROM */
	/**
	  EEPROM data is available at offsets 0 - 127.
	  Only the low 8 bits are actually stored.
	*/
	pic14_word ee[pic14_ee_len];
} pic14_program;

/** Hard configuration state for pic14 microprocessor */
typedef struct {
	/**
	  Oscilator calibration word, stored at 0x3ff.
	*/
	pic14_word osccal;
	
#define pic14_id_len 4u
	/**
	  Special configuration memory "User ID" words, at
	  configuration address 0x2000 - 0x2003.
	  Supposedly, only the low 7 bits are usable.
	*/
	pic14_word id[pic14_id_len];
	
	/**
	  Special configuration word, at 0x2007.
	*/
	pic14_word config;
	
} pic14_config;

/** All programmable state on a pic14 */
typedef struct {
	pic14_program program;
	pic14_config config;
} pic14_state;

/** Initialize this state to a reasonable power-up value.*/
void pic14_state_init(pic14_state *p);


/** Describes an address range that can be treated uniformly */
typedef struct {
	pic14_addr addr;  /* First word address */
	pic14_addr len;   /* Number of word addresses */
	pic14_word *data; /* Actual data (in a pic14_program) */
	const char *desc; /* Human-readable description */
} pic14_span;
#define pic14_program_nspans 5
/** Extract a list of spans from this program. */
void pic14_program_spans(pic14_state *p,pic14_span destspans[]);

/** Read this program from a .hex file. Returns NULL on 
   success, or an error message on error.
*/
const char *pic14_hex_read(pic14_state *p,FILE *src);

/** Write this program to a .hex file */
void pic14_hex_write(pic14_state *p,FILE *dest);

#endif
